#!/usr/bin/python

#=======================================
# Watch Program v 0.1
#=======================================

import ConfigParser
import string
import time
import win32api
import win32con
import win32event
import win32process


def loadConfig( file, config={} ):
    """
    returns a dictionary with key's of the form
    <section>.<option> and the values 
    """
    config = config.copy()
    cp = ConfigParser.ConfigParser()
    cp.read( file )
    for sec in cp.sections():
        name = string.lower( sec )
        for opt in cp.options( sec ):
            config[name + "_" + string.lower( opt )] = string.strip( cp.get( sec, opt ) )
    return config

def run_program ( pg_name ):
    info = win32process.CreateProcess( None, pg_name, None , None , 0 , win32process.NORMAL_PRIORITY_CLASS , None , None , win32process.STARTUPINFO() )
    return info[0]

def check_program( pg_handle_dict ):
    for handle, pg_info in pg_handle_dict.iteritems():
        time.sleep( .2 )
        rc = win32event.WaitForSingleObject( handle, 1000 ) 
        if rc == win32event.WAIT_OBJECT_0:
            print "Our processes closed in time.Run it again"
            print pg_info 
            del pg_handle_dict[handle]
            pg_handle = run_program( pg_info[1] )
            pg_handle_dict[pg_handle] = [pg_info[0], pg_info[1]]
            break
            #handle run_program(pg_command)
        else :
            print "Our processes is active"
            print pg_info
            
def main ():
    for pg_name, pg_cmd in pg.iteritems():
        #pg_name = pg_cmd
        pg_handle = run_program( pg_cmd )
        print "Run Program -->  %s" % pg_name
        pg_handle_dict[pg_handle] = [pg_name, pg_cmd]
        print pg_handle_dict
    while 1:
        check_program( pg_handle_dict )   
    
if __name__ == '__main__':
    global pg
    global pg_handle_dict
    pg_handle_dict = {}
    _ConfigDefault = {}
    pg = loadConfig( "config.ini", _ConfigDefault )
    #print pg
    main()
